# encoding: utf-8 -*-
# Python3 
# Author：xiang
# Time：2023-02-03 13:55
from dvadmin.utils.serializers import CustomModelSerializer
from quality_control.models import ProjectManageModel, DefectManageModel
from test_manage.models import CaseModuleModel
from test_manage.serializers import ModuleInitSerializer
from rest_framework.validators import UniqueValidator
from rest_framework import serializers
import datetime

class CustomDateField(serializers.DateField):
    def to_internal_value(self, value):
        if not value or value == '':
            return None
        return super().to_internal_value(value)


class ProjectManageModelSerializer(CustomModelSerializer):
    project_name = serializers.CharField(validators=[UniqueValidator(queryset=ProjectManageModel.objects.all(), message='项目名称不能重复')])
    project_key = serializers.CharField(validators=[UniqueValidator(queryset=ProjectManageModel.objects.all(), message='项目标识不能重复')])

    def create(self, validated_data):
        instance = super().create(validated_data)
        module_data = {
            "module_name": instance.project_name,
            "owner": instance.owner,
            "status": instance.status,
            "key": instance.project_key,
            "project_belong": None,
            "project_belong_id": None,
            "parent": None,
            "creator": instance.creator_id,
            "modifier": instance.modifier,
            "dept_belong_id": instance.dept_belong_id
        }
        serializer = ModuleInitSerializer(data=module_data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return instance

    def update(self, instance, validated_data):
        project_name = ProjectManageModel.objects.get(id=instance.id).project_name
        module = CaseModuleModel.objects.get(module_name=project_name)
        module.module_name = validated_data["project_name"]
        module.owner = validated_data["owner"]
        module.status = validated_data["status"]
        module.key = validated_data["project_key"]
        module.modifier = validated_data["modifier"]
        module.save()
        return super().update(instance, validated_data)

    class Meta:
        model = ProjectManageModel
        fields = '__all__'


class DefectManageModelSerializer(CustomModelSerializer):
    accident_time = CustomDateField(required=False)
    resolution_time = CustomDateField(required=False)

    def save(self, **kwargs):
        project_belong_id = CaseModuleModel.objects.get(id=self.validated_data['module_belong'].id).project_belong_id
        if project_belong_id is None:
            project_name = self.validated_data['module_belong'].module_name
            project_belong_id = ProjectManageModel.objects.get(project_name=project_name).id
        self.validated_data['project_belong_id'] = project_belong_id
        return super().save(**kwargs)

    class Meta:
        model = DefectManageModel
        fields = '__all__'


class ExportDefectSerializer(CustomModelSerializer):
    """
    缺陷导出 序列化器
    """
    defect_priority = serializers.CharField(source="get_defect_priority_display", read_only=True)
    defect_level = serializers.CharField(source="get_defect_level_display", read_only=True)
    defect_status = serializers.CharField(source="get_defect_status_display", read_only=True)
    accident_time = serializers.DateField(format="%Y-%m-%d", required=False, read_only=True)
    resolution_time = serializers.DateField(format="%Y-%m-%d", required=False, read_only=True)
    project_name = serializers.CharField(source="project_belong.project_name", read_only=True)
    module_name = serializers.CharField(source="module_belong.module_name", read_only=True)

    class Meta:
        model = DefectManageModel
        fields = (
            "defect_des",
            "defect_status",
            "defect_level",
            "defect_priority",
            "accident_time",
            "resolution_time",
            "defect_type",
            "effect_range",
            "cause_occurrence",
            "improvement_action",
            "project_name",
            "module_name",
            "tester",
            "developer",
            "reproduce_step",
        )